package com.yc.testupload.service;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.yc.testupload.util.RabbitMQConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

/**
 * 微信公众号发布任务消息生产者
 * 负责将发布任务发送到消息队列
 */
public class WechatPublishProducer {
    private static final Logger logger = LogManager.getLogger(WechatPublishProducer.class);
    private final String queueName;
    
    public WechatPublishProducer() {
        this.queueName = RabbitMQConfig.WECHAT_PUBLISH_QUEUE;
    }
    
    /**
     * 发送发布任务到消息队列
     * @param requestData 包含发布任务所需的所有数据
     * @return 任务ID
     */
    public String sendPublishTask(Map<String, Object> requestData) {
        String taskId = UUID.randomUUID().toString();
        
        try {
            // 获取RabbitMQ连接
            Connection connection = RabbitMQConfig.getConnection();
            
            // 创建通道
            try (Channel channel = connection.createChannel()) {
                // 声明队列（持久化）
                boolean durable = true; // 队列持久化
                channel.queueDeclare(queueName, durable, false, false, null);
                
                // 将任务ID添加到请求数据中
                requestData.put("taskId", taskId);
                requestData.put("status", "QUEUED");
                requestData.put("createTime", System.currentTimeMillis());
                
                // 将请求数据转换为JSON字符串
                String message = new JSONObject(requestData).toString();
                
                // 发送消息（持久化）
                channel.basicPublish("", queueName, null, message.getBytes("UTF-8"));
                
                logger.info("发布任务已发送到队列，任务ID: {}", taskId);
                return taskId;
            }
        } catch (IOException | TimeoutException e) {
            logger.error("发送发布任务到队列失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送发布任务失败: " + e.getMessage(), e);
        }
    }
    

}